<?php

class DocumentoController extends Zend_Controller_Action
{

    protected $documento;

    public function init()
    {
        $this->documento = new Documento();
    }

    public function indexAction()
    {
		$lista = Zend_Filter::filterStatic($this->_getParam('lista'), 'alpha');
        if(!$lista){$lista='simples';}
        $identity = Zend_Auth::getInstance()->getIdentity();
        $documentos = $this->documento->fetchAll();
        $table = new Zend_Db_Table('documento_mov');
        $docs = array();
        foreach($documentos as $v):
            $select = $table->select()
                ->where('documento_id=?',$v['id']);
            $origem = $table->fetchAll($select);
            $docs[$v['id']] = $origem;
        endforeach;
        $this->view->user = $identity;
        $this->view->data = $documentos;
        $this->view->origem = $docs;
        $this->view->lista = $lista;
    }

    public function pesquisaAction()
    {
		$form  = new Application_Form_DocumentoPesq(); 
		
		if ($this->getRequest()->isPost()) {
            $identity = Zend_Auth::getInstance()->getIdentity();
			$data = $this->getRequest()->getParams();
            $select = $this->documento->select();
            if($data['dt_inicio']):
                $date = new Zend_Date($data['dt_inicio'], null , 'pt_BR');
                $data['dt_inicio'] = $date->toString('yyyy-MM-dd');
                $select->where('data_recebimento>=?', $data['dt_inicio']);
            endif;
            if($data['dt_termino']):
                $date = new Zend_Date($data['dt_termino'], null , 'pt_BR');
                $data['dt_termino'] = $date->toString('yyyy-MM-dd');
                $select->where('data_recebimento<=?', $data['dt_termino']);
            endif;
            if($data['protocolo']):
                $select->where('protocolo like "%'.$data['protocolo'].'%"');
            endif;
            if($data['assunto']):
                $select->where('assunto like "%'.$data['assunto'].'%"');
            endif;
            if($data['origem']):
                $select->where('origem like "%'.$data['origem'].'%"');
            endif;
            if($data['destino']):
                $select->where('destino like "%'.$data['destino'].'%"');
            endif;
            if($data['numero']):
                $select->where('numero = ?', $data['numero']);
            endif;
            if($data['ano']):
                $select->where('ano = ?', $data['ano']);
            endif;
            $documentos = $this->documento->fetchAll($select);
            $table = new Zend_Db_Table('documento_mov');
            $docs = array();
            foreach($documentos as $v):
                $select = $table->select()
                    ->where('documento_id=?',$v['id']);
                $origem = $table->fetchAll($select);
                $docs[$v['id']] = $origem;
            endforeach;
            $this->view->user = $identity;
            $this->view->data = $documentos;
            $this->view->origem = $docs;
            $this->view->lista = 'simples';
            $this->render('index');
		}
		$this->view->form = $form;
    }

    public function detalheAction()
    {
		$doc_id = Zend_Filter::filterStatic($this->_getParam('doc_id'), 'int');
        $identity = Zend_Auth::getInstance()->getIdentity();
        $documento = $this->documento->find($doc_id)->current();
        $table = new Zend_Db_Table('documento_mov');
        $docs = array();
        $select = $table->select()
            ->where('documento_id=?',$documento['id']);
        $origem = $table->fetchAll($select);
        $docs[$documento['id']] = $origem;
        $usuarios = new Tri_Db_Table('usuario');
        $usuarios = $usuarios->fetchPairs('id','apelido');
        $this->view->usuarios = $usuarios;
        $this->view->user = $identity;
        $this->view->data = $documento;
        $this->view->origem = $docs;
    }

    public function movimentacaoAction()
    {
		$doc_id = Zend_Filter::filterStatic($this->_getParam('doc_id'), 'int');
        $identity = Zend_Auth::getInstance()->getIdentity();
        $atual = $this->documento->find($doc_id)->current();
        $table = new Zend_Db_Table('documento_mov');
        $select = $table->select()
            ->where('documento_id=?',$doc_id);
        $origem = $table->fetchAll($select);
        $lista = array();
        foreach($origem as $v):
            $lista[$v['documento_id']][] = $v;
        endforeach;
        $usuarios = new Tri_Db_Table('usuario');
        $usuarios = $usuarios->fetchPairs('id','apelido');
        $this->view->usuarios = $usuarios;
        $this->view->atual = $atual;
        $this->view->origem = $lista;
        $this->_helper->layout->disableLayout(); 
        $this->view->user = $identity;
    }
    
    public function formAction()
    {
		$id    = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
		$form  = new Application_Form_Documento(); 
        $form->setAction('documento/save');
		
		if ($id) {
			$data = $this->documento->find($id)->current()->toArray();
            if($data['data']):
                $date = new Zend_Date($data['data'], null , 'pt_BR');
                $data['data'] = $date->toString('dd/MM/yyyy');
            endif;
            if($data['data_recebimento']):
                $date = new Zend_Date($data['data_recebimento'], null , 'pt_BR');
                $data['data_recebimento'] = $date->toString('dd/MM/yyyy');
            endif;
			$form->populate($data);
		}
		$this->view->form = $form;
    }
    
    public function formMovimentacaoAction()
    {
		$id     = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
		$doc_id = Zend_Filter::filterStatic($this->_getParam('doc_id'), 'int');
		$form  = new Application_Form_DocumentoMov(); 
        $form->setAction('documento/save-movimentacao');
        $table = new Zend_Db_Table('documento_mov');
		
		if ($id) {
			$data = $table->find($id)->current()->toArray();
            $doc_id = $data['documento_id'];
            $date = new Zend_Date($data['dt_criacao'], null , 'pt_BR');
            $data['dt_criacao'] = $date->toString('dd/MM/yyyy');
			$form->populate($data);
		} else
        {
            $identity = Zend_Auth::getInstance()->getIdentity();
            $form->getElement('documento_id')->setValue($doc_id);
            $form->getElement('responsavel_id')->setValue($identity->id);
        }
		$this->view->form = $form;

        $this->_helper->layout->disableLayout(); 
        $this->render('form-mov');
    }
    
	public function saveAction()
	{
		if ($this->getRequest()->isPost()) {
			$form  = new Application_Form_Documento(); 
			
			if ($form->isValid($this->_getAllParams())) {
				$data = $form->getValues();
                if($data['data']):
                    $locale = new Zend_Locale('pt_BR');
                    $date = new Zend_Date($data['data'], null, $locale);
                    $data['data'] = $date->toString('yyyy-MM-dd');                    
                endif;
                if($data['data_recebimento']):
                    $date = new Zend_Date($data['data_recebimento'], null , 'pt_BR');
                    $data['data_recebimento'] = $date->toString('yyyy-MM-dd');
                else:
                    $data['data_recebimento'] = null;
                endif;
                if($this->protocoloRepetido($data)):
                    $this->_helper->flashMessenger->addMessage('Atenção! Este protocolo já existe!');
                    $this->_redirect('documento/form/id/'.$data['id']);
                else:
                    if (isset($data['id']) && $data['id']) {
                        $this->documento->update($data, array('id = ?' => $data['id']));
                    } else {
                        $identity = Zend_Auth::getInstance()->getIdentity();
                        $data['responsavel_id'] = $identity->id;
                        $this->documento->insert($data);
                    }
                    $this->_redirect('documento/index');
                endif;
			}
			
			$this->view->form = $form;
			$this->render('form');
		}
	}
	
	public function deleteAction()
	{
		$id = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
		
		if ($id) {
			$this->documento->delete(array('id = ?' => $id));
		}
		
		$this->_redirect('documento/index');
	}

	public function saveMovimentacaoAction()
	{
		if ($this->getRequest()->isPost()) {
			$form  = new Application_Form_DocumentoMov(); 
            $data = $this->_getAllParams();
			if ($form->isValid($this->_getAllParams())) {
                $data = $form->getValues();
                $date = new Zend_Date($data['dt_criacao'], null , 'pt_BR');
                $data['dt_criacao'] = $date->toString('yyyy-MM-dd');
                $table = new Zend_Db_Table('documento_mov');
				if (isset($data['id']) && $data['id']) {
					$table->update($data, array('id = ?' => $data['id']));
				} else {
                    $identity = Zend_Auth::getInstance()->getIdentity();
                    $data['responsavel_id'] = $identity->id;
					$table->insert($data);
				}
			}
            $this->_redirect('documento/movimentacao/doc_id/'.$data['documento_id']);
    	}
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();
	}
	
	public function movimentacaoDeleteAction()
	{
		$id = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
		
		if ($id) {
            $table = new Zend_Db_Table('documento_mov');
            $atual = $table->find($id)->current();
			$table->delete(array('id = ?' => $id));
    		$this->_redirect('documento/movimentacao/doc_id/'.$atual['documento_id']);
		}
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();
	}
    
    protected  function protocoloRepetido($data)
    {
        if(trim($data)):
            $select = $this->documento->select()
                ->where('not id = ?',$data['id'])
                ->where('protocolo = ?',$data['protocolo']);
            $result = $this->documento->fetchAll($select);
            return(count($result));
        else:
            return false;
        endif;
    }

}